﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using Autofac;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using WebToolService;
using System.Web.Compilation;

namespace WebTool
{
    public class BootStrap
    {
        public Autofac.IContainer MyContainer { get; private set; }
        private ContainerBuilder Builder;

        public void Configure()
        {
            this.Builder = new ContainerBuilder();
            OnConfigure();
            if (this.MyContainer == null)
            {
                this.MyContainer = Builder.Build();
            }
            else
            {
                Builder.Update(this.MyContainer);
            }
            //This tells the MVC application to use myContainer as its dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(this.MyContainer));
        }
        protected virtual void OnConfigure()
        {
            //This is where you register all dependencies
            //The line below tells autofac, when a controller is initialized, pass into its constructor, the implementations of the required interfaces
            Builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            RegisterWebToolRepositoryService();
        }
        private void RegisterWebToolRepositoryService()
        {
            RegisterAssemblyName("WebToolService", "Service");
        }
        private void RegisterAssemblyName(string assemblyName, string className)
        {
            Assembly serviceAssemblies = Assembly.Load(assemblyName);
            Builder.RegisterAssemblyTypes(serviceAssemblies).Where(t => t.Name.EndsWith(className)).InstancePerLifetimeScope();
        }
    }
}